package com.xiao.xin.core.Interceptor;

import cn.hutool.core.util.ObjUtil;
import com.xiao.xin.core.Util.JwtUtil;
import com.xiao.xin.core.Util.UserThreadLocal;
import com.xiao.xin.core.exception.UserLoginException;
import com.xiao.xin.core.domain.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.HandlerInterceptor;


/***
 * 注册拦截器
 */
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
        User user = JwtUtil.parseToken(authorization);
        if (ObjUtil.isEmpty(user)) throw new UserLoginException("用户未授权信息,请重新登录");
        UserThreadLocal.setUser(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.removeUser();
    }
}
